package artid.com.arttogoa.adapter;

import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.PopupWindow.OnDismissListener;
import artid.com.arttogoa.R;
import artid.com.arttogoa.barcode.Cache;
import artid.com.arttogoa.parser.AppItem;
import artid.com.arttogoa.parser.ReplyParser;
import artid.com.arttogoa.util.CircleImageView;
import artid.com.arttogoa.util.NetUtils;
import artid.com.arttogoa.volley.VolleyBasic;
import artid.com.arttogoa.volley.VolleyCallback;
import artid.com.arttogoa.volley.VolleyData;
import artid.com.arttogoa.volley.VolleyMap;
import com.android.volley.VolleyError;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;

/**
 * 
 *    
 * 项目名称：ArtworkArtA   
 * 类名称   ：ReplyAdapter   
 * 类描述   ：艺术家回复列表适配器 
 * 创建人   ：耿卫斌   
 * 创建时间：2016-5-20 下午4:46:12   
 *
 */
public class ReplyAdapter extends BaseAdapter {
	private Activity mActivity;
	private Context mContext;
	private List<ReplyParser> list;
	private int setMessagePosition;
	private String user;
	public  PopupWindow window;

	public ReplyAdapter(Activity mActivity, List<ReplyParser> list) {
		super();
		this.mActivity = mActivity;
		this.list = list;
		mContext=mActivity;
	}

	public void notifyData(String message){
		list.get(setMessagePosition).setContent(message);
		notifyDataSetChanged();
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return list.size();
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return list.get(position);
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}
	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		ViewHolder holder = null;
		View v = convertView;
		if (v == null) {
			holder = new ViewHolder();
			v = LayoutInflater.from(mContext).inflate(R.layout.item_reply, null);
			holder.icon=(CircleImageView) v.findViewById(R.id.itemReply_icon);
			holder.img=(ImageView) v.findViewById(R.id.itemReply_img);
			holder.name=(TextView) v.findViewById(R.id.itemReply_name);
			holder.com_create_time=(TextView) v.findViewById(R.id.itemReply_com_create_time);
			holder.com_content=(TextView) v.findViewById(R.id.itemReply_com_content);
			holder.myComment=(TextView) v.findViewById(R.id.itemReply_myComment);
			holder.title=(TextView) v.findViewById(R.id.itemReply_title);
			holder.replyBtn=(TextView) v.findViewById(R.id.itemReply_replyBtn);
			holder.myCommentLL=(LinearLayout) v.findViewById(R.id.itemReply_myCommentLL);
			v.setTag(holder);
		} else {
			holder = (ViewHolder) v.getTag();
		}
		ImageLoader.getInstance().displayImage(list.get(position).getImgurl()
				+ "_"+ NetUtils.dip2px(mContext, 100)+"x"+NetUtils.dip2px(mContext, 100)+".png"
				, holder.icon,options);
		ImageLoader.getInstance().displayImage(list.get(position).getPic_url()
				+ "_"+ (Integer.parseInt(NetUtils.getDisplayMetrics((Activity)mContext).get(NetUtils.DM_WIDTH)) / 1) + "x10.png", 
				holder.img,options);
		holder.name.setText(list.get(position).getRealname());
		holder.com_create_time.setText(list.get(position).getCom_create_time());
		holder.com_content.setText(list.get(position).getCom_content());
		holder.title.setText(list.get(position).getTitle());
		if(!StringUtils.isEmpty(list.get(position).getContent()) && !"null".equals(list.get(position).getContent())){
			holder.myCommentLL.setVisibility(View.VISIBLE);
			holder.myComment.setText("回复："+list.get(position).getContent());
		}else{
			holder.myCommentLL.setVisibility(View.INVISIBLE);
		}
		holder.replyBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				setMessagePosition=position;
				showPopwindow(mContext, v, R.id.itemReply_replyBtn, list.get(position).getCom_id(),list.get(position).getRealname());
			}
		});
		return v;
	}
	class ViewHolder {
		CircleImageView icon;
		ImageView img;
		TextView name,com_create_time,com_content,myComment,title,replyBtn;
		LinearLayout myCommentLL;
	}

	/**
	 * 字符串截取
	 * @param str
	 * @param splitsign
	 * @return
	 */
	@SuppressWarnings("unchecked")  
	public static String[] split(String str, String splitsign) {  
		int index;  
		if (str == null || splitsign == null)  
			return null;  
		ArrayList al = new ArrayList();  
		while ((index = str.indexOf(splitsign)) != -1) {  
			al.add(str.substring(0, index));  
			str = str.substring(index + splitsign.length());  
		}  
		al.add(str);  
		return (String[]) al.toArray(new String[0]);  
	}  

	/**
	 * 回复
	 */
	private void postReply(String id,final String content){
		VolleyBasic.getInstance(mActivity).post(Cache.replyComment,
				VolleyMap.getInstance().replyComment(id, content), AppItem.class,new VolleyCallback() {
			public void onSuccess(VolleyData vd) {
				// TODO Auto-generated method stub
				System.out.println(vd.getJson());
				if(vd.getCode()==VolleyData.Success){
					notifyData(content);
					Intent i=new Intent("com.Push.receiver");
					mContext.sendBroadcast(i);
				}
			}
			public void onError(VolleyError volleyError) {

			}
		});
	}


	public  void showPopwindow(final Context mContext,View v,int ViewId,final String id,String hint) {
		// 利用layoutInflater获得View
		LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View view = inflater.inflate(R.layout.popupwindow_comment, null);
		// 下面是两种方法得到宽度和高度 getWindow().getDecorView().getWidth()
		window = new PopupWindow(view,
				WindowManager.LayoutParams.MATCH_PARENT,
				WindowManager.LayoutParams.WRAP_CONTENT);
		// 设置popWindow弹出窗体可点击，这句话必须添加，并且是true
		window.setFocusable(true);
		window = new PopupWindow(view, WindowManager.LayoutParams.FILL_PARENT,WindowManager.LayoutParams.WRAP_CONTENT,false);
		//设置可以获取焦点，否则弹出菜单中的EditText是无法获取输入的
		window.setFocusable(true);
		//这句是为了防止弹出菜单获取焦点之后，点击activity的其他组件没有响应
		window.setBackgroundDrawable(new BitmapDrawable()); 
		//防止虚拟软键盘被弹出菜单遮住
		window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
		// 在底部显示
		window.showAtLocation(v.findViewById(ViewId),
				Gravity.BOTTOM, 0, 0);
		// 这里检验popWindow里的button是否可以点击
		showKeyboard(mContext);
		TextView first = (TextView) view.findViewById(R.id.popupwindow_comment_Button);
		final EditText mEditText=(EditText) view.findViewById(R.id.popupwindow_comment_mEditText);
		mEditText.setHint("回复:"+hint);
		first.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Log.d("log", "第一个按钮被点击了");
				postReply(id, mEditText.getText().toString());
				window.dismiss();
			}
		});
		//popWindow消失监听方法
		window.setOnDismissListener(new OnDismissListener() {

			@Override
			public void onDismiss() {
				System.out.println("popWindow消失");
				showKeyboard(mContext);
			}
		});
	}

	/**
	 * 关闭软键盘
	 * @param mContext
	 */
	public static void showKeyboard(Context mContext){
		InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);  
		imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);  
	}
	
	DisplayImageOptions options = new DisplayImageOptions.Builder()
	.showImageForEmptyUri(R.drawable.yspba_img_mor) // 设置图片Uri为空或是错误的时候显示的图片
	.showImageOnFail(R.drawable.yspba_img_mor) // 设置图片加载或解码过程中发生错误显示的图片
	.resetViewBeforeLoading(false)  // default 设置图片在加载前是否重置、复位
	.delayBeforeLoading(0)  // 下载前的延迟时间
	.cacheInMemory(false) // default  设置下载的图片是否缓存在内存中
	.cacheOnDisk(true) // default  设置下载的图片是否缓存在SD卡中
	.considerExifParams(false) // default
	.imageScaleType(ImageScaleType.EXACTLY) // default 设置图片以如何的编码方式显示
	.bitmapConfig(Bitmap.Config.RGB_565) // default 设置图片的解码类型
	//		.displayer(new SimpleBitmapDisplayer()) // default  还可以设置圆角图片new RoundedBitmapDisplayer(20)
	.build();

}
